﻿using M_Quality.API.Application.Command.QualitygroupCommand;
using M_Quality.Domain;
using M_Quality.Domain.Dto;
using M_Quality.Repository.Interface;
using MediatR;

namespace M_Quality.API.Application.CommandHandler.QualitygroupHandler
{
    public class QualitygroupShowCommandHandler : IRequestHandler<QualitygroupShowCommand, PageDto<Qualitygroup>>
    {
        protected readonly IQualitygroupRepository qualitygroupRepository;

        public QualitygroupShowCommandHandler(IQualitygroupRepository qualitygroupRepository)
        {
            this.qualitygroupRepository = qualitygroupRepository;
        }

        public async Task<PageDto<Qualitygroup>> Handle(QualitygroupShowCommand request, CancellationToken cancellationToken)
        {
  var res = await qualitygroupRepository.GetAsync(o =>  o.IsDeleted == false);
         
            if (!string.IsNullOrEmpty(request.QualitygroupBH))
            {
                res = res.Where(o => o.QualitygroupBH .Contains(request.QualitygroupBH)).ToList();
            }
            if (!string.IsNullOrEmpty(request.QualitygroupName))
            {
                res = res.Where(o => o.QualitygroupName.Contains(request.QualitygroupName)).ToList();
            }
            if (request.Pagesize == null)
            {
                request.Pagesize = res.Count();
            }
            if (request.Pageindex == null)
            {
                request.Pageindex = 1;
            }
            PageDto<Qualitygroup> page = new PageDto<Qualitygroup>();
            var size = request.Pagesize;
            var index = request.Pageindex;
            page.TotalCount = res.Count();
            page.PageCount = (int)Math.Ceiling(page.TotalCount * 1.0 / (int)size);
            page.list = res.OrderByDescending(o => o.QualitygroupId).Skip(((int)index - 1) * (int)size).Take((int)size).ToList();
            return page;
        }
    }
}
